import { observable, action } from "mobx-miniprogram";
import { getDefaultEnvId } from "../utils/env";
import { fetchBootstrap } from "../services/bootstrap";
import type {
  CategoryItem,
  MenuItem,
  OrderLineItem,
  OrderRecord,
  UserProfile,
  UserRole,
} from "../types/entities";

export const globalStore = observable({
  envId: getDefaultEnvId(),
  loading: false,
  role: "guest" as UserRole,
  userProfile: null as UserProfile | null,
  categories: [] as CategoryItem[],
  menu: [] as MenuItem[],
  orders: [] as OrderRecord[],
  cart: [] as OrderLineItem[],
  cartNote: "",
  activeOrderId: "",

  get isChef() {
    return this.userProfile?.role === "chef";
  },

  get isDiner() {
    return this.userProfile?.role === "diner";
  },

  setRole: action(function (role: UserRole) {
    if (this.userProfile) {
      this.role = this.userProfile.role;
      return;
    }
    this.role = role;
  }),

  setUserProfile: action(function (profile: UserProfile | null) {
    this.userProfile = profile;
    this.role = profile?.role ?? "guest";
  }),

  setCategories: action(function (list: CategoryItem[]) {
    this.categories = list;
  }),

  setMenu: action(function (list: MenuItem[]) {
    this.menu = list;
  }),

  updateMenuSnapshot: action(function (item: MenuItem) {
    const index = this.menu.findIndex((menuItem) => menuItem._id === item._id);
    if (index >= 0) {
      this.menu[index] = item;
    } else {
      this.menu.unshift(item);
    }
  }),

  removeMenuSnapshot: action(function (menuId: string) {
    this.menu = this.menu.filter((item) => item._id !== menuId);
  }),

  setOrders: action(function (list: OrderRecord[]) {
    this.orders = list;
  }),

  updateOrderSnapshot: action(function (order: OrderRecord) {
    const index = this.orders.findIndex((item) => item._id === order._id);
    if (index >= 0) {
      this.orders[index] = order;
    } else {
      this.orders.unshift(order);
    }
  }),

  setActiveOrder: action(function (orderId: string) {
    this.activeOrderId = orderId;
  }),

  setCart: action(function (items: OrderLineItem[]) {
    this.cart = items;
  }),

  setCartNote: action(function (note: string) {
    this.cartNote = note;
  }),

  clearCart: action(function () {
    this.cart = [];
    this.cartNote = "";
  }),

  logout: action(function () {
    this.userProfile = null;
    this.role = "guest";
    this.categories = [];
    this.menu = [];
    this.orders = [];
    this.cart = [];
    this.cartNote = "";
    this.activeOrderId = "";
  }),

  initAppData: action(async function () {
    if (this.loading) return;
    this.loading = true;
    try {
      const data = await fetchBootstrap();
      this.envId = data.envId || this.envId;
      this.userProfile = data.userProfile;
      this.role = data.userProfile?.role ?? "guest";
      this.categories = data.categories ?? [];
      this.menu = data.menu ?? [];
      this.orders = data.orders ?? [];
    } catch (error) {
      console.error("初始化数据失败", error);
    } finally {
      this.loading = false;
    }
  }),
});
